﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Xml.Serialization;

namespace TibcoWinform
{
    public class SerializableHelper
    {
        public static void Save<T>(T value, string filename)
        {
            var jsonstr = JsonConvert.SerializeObject(value, Formatting.Indented);
            //var json = new JavaScriptSerializer().Serialize(value);
            using (FileStream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (TextWriter writer = new StreamWriter(file, new UTF8Encoding()))
                    writer.Write(jsonstr);
            }
        }
        public static void Save2<T>(T value, string filename)
        {
            //var jsonstr = JsonConvert.SerializeObject(str, Formatting.Indented);
            var jsonstr = new JavaScriptSerializer().Serialize(value);
            using (FileStream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (TextWriter writer = new StreamWriter(file, new UTF8Encoding()))
                    writer.Write(jsonstr);
            }
        }
        public static T Read<T>(string filename)
        {
            return JsonConvert.DeserializeObject<T>(File.ReadAllText(filename));
            //return JsonConvert.DeserializeObject<T>(JsonStr(filename));
        }
        private static string JsonStr(string filename)
        {
            var str = "";
            using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (TextReader writer = new StreamReader(file, new UTF8Encoding(false)))
                    str = writer.ReadToEnd();
            }
            return str;
        }
        public static void SaveToXML<T>(T value)
        {
            var reader = new XmlSerializer(typeof(T));
            //写入文件
            using (var fs = File.OpenWrite("UserInfo.xml"))
            {
                reader.Serialize(fs, value);
            }
        }
        public static T ReadFromXML<T>()
        {
            var reader = new XmlSerializer(typeof(T));

            using (var fs = File.OpenRead("UserInfo.xml"))
            {
                var result = (T)reader.Deserialize(fs);
                return result;
            }
        }
    }
}
